import React, { Component, useRef } from 'react'
import { SearchOutlined } from '@ant-design/icons';
import { Form, Input, Space, Button, Select, DatePicker, Tabs } from 'antd'
import _ from 'lodash'
import TheButton from '@/components/TheButton'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheDialog from '@/components/TheDialog'
import { apiShopSalesReturnPage } from '@/request/orderManagement'
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable.js';

const { RangePicker } = DatePicker
const { TabPane } = Tabs

const SearchHeader = ({ getValue, orderCode, toExport }) => {
  const formRef = useRef()
  const orderCode11 = orderCode
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0]) + ' 00:00:00'
      values.createTimeEnd = getDateTime3(values.time[1]) + ' 23:59:59'
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      orderCode: '',
      shopSalesReturnId: '',
      moneyStatus: null,
      time: []
    })
    getValue({})
  }

  const toExportTable = () => {
    let data = formRef.current.getFieldsValue()
    if (data.time && data.time.length) {
      data.createTimeStart = getDateTime3(data.time[0]) + ' 00:00:00'
      data.createTimeEnd = getDateTime3(data.time[1]) + ' 23:59:59'
    }
    delete (data.time)
    _.forIn(data, (v, k) => {
      if (!v) {
        delete (data[k])
      }
    })
    toExport(data)
  }
  return (
    <Form ref={formRef} onFinish={onFinish} layout="inline" initialValues={{
      orderCode: orderCode11
    }}>
      <Form.Item name="orderCode">
        <Input style={{ width: 140 }} placeholder='请输入订单号' suffix={<SearchOutlined />} />
      </Form.Item>
      <Form.Item name="returnCode">
        <Input style={{ width: 140 }} placeholder='请输入退单号' suffix={<SearchOutlined />} />
      </Form.Item>
      <Form.Item name="moneyStatus">
        <Select allowClear options={[
          {
            value: 'N',
            label: '仅退款'
          },
          {
            value: 'Y',
            label: '退货退款'
          }
        ]} placeholder={"请选择退款类型"} width={160} />
      </Form.Item>
      <Form.Item name="time">
        <RangePicker placeholder={['申请时间', '申请时间']} />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button htmlType="submit" type="primary">搜索</Button>
          <Button onClick={reset}>重置</Button>
          <Button onClick={toExportTable}>导出</Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default class MallChangeback extends Component {
  constructor(props) {
    super(props)
    this.SearchHeaderRef = React.createRef()
    this.state = {
      searchOrderCode: '',
      columns: [
        {
          title: '订单编号',
          dataIndex: 'orderCode',
          key: 'orderCode'
        },
        {
          title: '退单编号',
          dataIndex: 'returnCode',
          key: 'returnCode'
        },
        {
          title: '买家昵称',
          dataIndex: 'nickName',
          key: 'nickName'
        },
        {
          title: '退款商品',
          dataIndex: 'goodsName',
          key: 'goodsName',
          render: (text, record) => {
            let arr = '/'
            if (typeof record.goodsSkuJson === 'string') {
              try {
                let goodsSku = JSON.parse(record.goodsSkuJson)
                if (typeof goodsSku === 'object' && goodsSku) {
                  arr = goodsSku.hasOwnProperty('skuAttribute') && goodsSku.skuAttribute.map(v => {
                    return v.value
                  })
                }
              } catch (e) {
                console.log(e)
              }
            }
            return <div>
              <div>{text}</div>
              <div>{arr}</div>
            </div>
          }
        },
        {
          title: '商家名称',
          dataIndex: 'storeName',
          key: 'storeName'
        },
        {
          title: '退款类型',
          dataIndex: 'moneyStatus',
          key: 'moneyStatus',
          render: (text, record) => {
            let label = '';
            switch (text) {
              case 'N':
                label = '仅退款';
                break;
              case 'Y':
                label = '退货退款';
                break;
            }
            return label;
          }
        },
        {
          title: '订单金额（元）',
          dataIndex: 'orderPriceTotal',
          key: 'orderPriceTotal',
          render: (text, record) => {
            return <React.$Price price={text} />
          }
        },
        {
          title: '实付金额（元）',
          dataIndex: 'orderPayPrice',
          key: 'orderPayPrice',
          render: (text, record) => {
            return <React.$Price price={text} />
          }
        },
        {
          title: '退款金额（元）',
          dataIndex: 'detailPayPrice',
          key: 'detailPayPrice',
          render: (text, record) => {
            return <React.$Price price={text} />
          }
        },
        {
          title: '申请时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '退款状态',
          dataIndex: 'salesStatus',
          key: 'salesStatus',
          render: (text, record) => {
            let label = ""
            switch (parseInt(text)) {
              case 1:
              case 2:
              case 3:
                label = "退款中";
                break;
              case 4:
                label = '退款失败';
                break;
              case 7:
                label = '退款取消';
                break;
              case 9:
                label = '退款成功';
                break;
              case 0:
                label = '退款关闭';
                break;
              default: ;
            }
            return label;
          }
        },
        {
          title: '操作',
          fixed: 'right',
          render: (text, record) => {
            return <>
              <TheButton hasPermi={['order:mallChargeback:view']} onClick={() => this.props.history.push(`/order/chargeback/mallDetails/${record.shopSalesReturnId}`)}>查看订单</TheButton>
            </>
          }
        }
      ],
      dataSource: [],
      tabData: [
        {
          key: "",
          tab: '全部'
        },
        {
          key: 1,
          tab: '退款中'
        },
        {
          key: 9,
          tab: '退款成功'
        },
        {
          key: 4,
          tab: '退款失败'
        },
        {
          key: 7,
          tab: '退款取消'
        },
        {
          key: 0,
          tab: '退款关闭'
        },
      ],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10
      },
      pageData7: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
      pageData4: {
        pageNo: 1,
        pageSize: 10
      },

      pageData0: {
        pageNo: 1,
        pageSize: 10
      },
      total1: 0,
      total9: 0,
      total4: 0,
      total0: 0,
      searchValue: {},
      salesStatus: ""
    }
  }

  componentDidMount() {
    console.log(this.props, 'this.props.match.params.orderCode');
    if (this.props.location.hasOwnProperty('query')) {
      this.setState({
        searchOrderCode: this.props.location.query.orderCode,
        searchValue: {
          orderCode: this.props.location.query.orderCode
        },
      }, () => {
        this.getData()
      })
    } else {
      if (localStorage.getItem("key")) {
        this.setState({
          salesStatus: localStorage.getItem("key")
        }, () => {
          this.getData()
        })
      } else {
        this.getData()
      }
    }

  }
  getData = async () => {
    const { searchValue, salesStatus } = this.state
    let res = await apiShopSalesReturnPage({ salesStatus, ...searchValue, ...this.state[`pageData${salesStatus}`] })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: res.data,
        [`pageData${salesStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`total${salesStatus}`]: res.totalCount
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    const { salesStatus } = this.state
    this.setState({
      [`pageData${salesStatus}`]: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  }
  getValue = value => {
    const { salesStatus } = this.state
    this.setState({
      [`pageData${salesStatus}`]: {
        pageNo: 1,
        pageSize: 10
      },
      searchValue: value
    }, () => {
      this.getData()
    })
  }
  changeKey = key => {
    localStorage.setItem("key", key)
    this.setState({
      salesStatus: key
    }, () => {
      this.getData()
    })
  }

  toExport = async (value) => {
    const { salesStatus } = this.state
    await apiShopSalesReturnPage({ pageNo: 1, pageSize: 5000, ...value, salesStatus }).then(res => {
      if (res.code === 0 && res.data) {
        console.log(res.data);
        let th_arr = [
          {
            title: '商城退单列表',
            prop: '',
            children: [
              {
                title: '订单编号',
                prop: 'orderCode',
              },
              {
                title: '退单编号',
                prop: 'returnCode',
              },
              {
                title: '买家昵称',
                prop: 'nickName',
              },
              {
                title: '退款商品',
                prop: 'goodsName',
              },
              {
                title: '商家名称',
                prop: 'storeName',
              },
              {
                title: '退款类型',
                prop: 'moneyStatus',
              },
              {
                title: '订单金额（元）',
                prop: 'orderPriceTotal',
                valueType: 'number'
              },
              {
                title: '实付金额（元）',
                prop: 'orderPayPrice',
                valueType: 'number'
              },
              {
                title: '退款金额（元）',
                prop: 'detailPayPrice',
                valueType: 'number'
              },
              {
                title: '申请时间',
                prop: 'createTime',
              },
              {
                title: '退款状态',
                prop: 'salesStatus',
              },
            ]
          }
        ]
        let tb_arr = []
        res.data.forEach(item => {
          let salesStatus = ""
          switch (item.salesStatus) {
            case '1':
            case '2':
            case '3':
              salesStatus = "退款中";
              break;
            case '4':
              salesStatus = '退款失败';
              break;
            case '7':
              salesStatus = '退款取消';
              break;
            case '9':
              salesStatus = '退款成功';
              break;
            case '0':
              salesStatus = '退款关闭';
              break;
            default: ;
          }
          let moneyStatus = '';
          switch (item.moneyStatus) {
            case 'N':
              moneyStatus = '仅退款';
              break;
            case 'Y':
              moneyStatus = '退货退款';
              break;
          }
          let arr = '/'
          if (typeof item.goodsSkuJson === 'string') {
            try {
              let goodsSku = JSON.parse(item.goodsSkuJson)
              if (typeof goodsSku === 'object' && goodsSku) {
                arr = goodsSku.hasOwnProperty('skuAttribute') && goodsSku.skuAttribute.map(v => {
                  return v.value
                })
              }
            } catch (e) {
              console.log(e)
            }
          }
          tb_arr.push({
            orderCode: item.orderCode || '/',
            returnCode: item.returnCode || '/',
            nickName: item.nickName,
            goodsName: item.goodsName + ',' + arr,
            storeName: item.storeName,
            moneyStatus: moneyStatus,
            orderPriceTotal: item.orderPriceTotal !== null ? React.$transNum(item.orderPriceTotal, 2, -2) : 0,
            orderPayPrice: item.orderPayPrice !== null ? React.$transNum(item.orderPayPrice, 2, -2) : 0,
            detailPayPrice: item.detailPayPrice !== null ? React.$transNum(item.detailPayPrice, 2, -2) : 0,
            createTime: item.createTime || '/',
            salesStatus: salesStatus
          })
        });
        exportSheetTable({ fileName: '商城退单列表', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
      }
    })
  }
  render() {
    const { columns, tabData, dataSource, salesStatus, searchOrderCode } = this.state
    return (
      <div className='p-layout-box'>
        <Tabs activeKey={salesStatus} onChange={this.changeKey} tabBarExtraContent={<SearchHeader ref={this.SearchHeaderRef} getValue={this.getValue} orderCode={searchOrderCode} toExport={this.toExport} />}>
          {
            tabData.map(v => {
              return <TabPane key={v.key} tab={v.tab}>
                <div className="p-layout-content-pagination">
                  <TheTable scroll={{ x: 'max-content', y: '58vh' }} columns={columns} dataSource={dataSource} />
                  <ThePagination
                    pageNo={this.state[`pageData${v.key}`].pageNo}
                    pageSize={this.state[`pageData${v.key}`].pageSize}
                    total={this.state[`total${v.key}`]}
                    pageChange={this.pageChange}
                  />
                </div>
              </TabPane>
            })
          }
        </Tabs>
      </div>
    )
  }
}
